/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 2/19/2010
*/

trigger LeadSharkPool on Lead (before insert, before update, after insert, after update, after delete) {
	/*
	ID leadRecordTypeId = LeadDedupeHelper.GetLocalAdsLeadRecordType();
	String Queue_Prefix = LeadSharkpoolClass.getQueue_Prefix();		
	if(trigger.isBefore){
	   List<Clock__c> upsert_clocks_in_before = new List<Clock__c>();		
	   if(LeadSharkpoolClass.getIsFirstBefore())	{	   
		    LeadSharkpoolClass.setIsFirstBefore(false);	
			
			Set<ID> ownerIds = new Set<ID>();
			Map<Id, Lead> update_leads = new Map<Id, Lead>();
			List<Messaging.SingleEmailMessage> messages = new List<Messaging.SingleEmailMessage>();
			
			if(trigger.isInsert){
				for(Lead l : trigger.new){
					String s = string.valueof(l.OwnerId);
					Boolean isMatched = (l.RecordTypeId == leadRecordTypeId) && !LeadSharkpoolClass.ExLeadSourceNames.contains(l.LeadSource)
					                 && !LeadSharkpoolClass.ExLeadStatusNames.contains(l.Status)
					                 && (s.substring(0, 3) != Queue_Prefix);                                       	
					if(isMatched){
						l.Latest_Owner_Change_Date__c = DateTime.now();
						l.Is7DaysEnabled__c = true;
					}
				}	
			}else if(trigger.isUpdate){
				for(Lead l : trigger.new){
					String s = string.valueof(l.OwnerId);
					Boolean isMatched = (l.RecordTypeId == leadRecordTypeId) && !LeadSharkpoolClass.ExLeadSourceNames.contains(l.LeadSource)
					                 && !LeadSharkpoolClass.ExLeadStatusNames.contains(l.Status)
					                 && (s.substring(0, 3) != Queue_Prefix);                                        	
					if(isMatched){
						update_leads.put(l.Id, l);
						ownerIds.add(l.OwnerId);
					}
				}
			}				
			
			System.debug('Test update_leads.isEmpty() = ' + update_leads.isEmpty());	
			if(!update_leads.isEmpty()){
				Set<ID> queueIds = new Set<ID>();
				Map<String, ID> SFAsQueueIDs = new Map<String, ID>();                                                            
				Map<ID, Group> queues = new Map<ID, Group>([select Id, Name 
				                                            from  Group 
				                                            where Name IN : LeadSharkpoolClass.QueueNameSFAs.keySet() 
				                                              and Type = 'Queue']);
				for(Group g : queues.values()){
					queueIds.add(g.Id);
					List<String> sfas = LeadSharkpoolClass.QueueNameSFAs.get(g.Name);
					for(String sfa : sfas){
						SFAsQueueIDs.put(sfa, g.Id);
					}	
				}
				
				Map<ID, ID> ownerIDsQueueIDs = new Map<ID, ID>();                                                            
				User[] users = [select ID, SFA_Office__c from User where ID IN : ownerIds];
				for(User u : users){
					if(u.SFA_Office__c != '' && SFAsQueueIDs.containsKey(u.SFA_Office__c)){
						ownerIDsQueueIDs.put(u.Id, SFAsQueueIDs.get(u.SFA_Office__c));
					}else{
						ownerIDsQueueIDs.put(u.Id, SFAsQueueIDs.get(LeadSharkpoolClass.SFA_Office_Missing));
					}			
				}
				
				List<Clock__c> extClocks = new List<Clock__c>([select Id, Lead__c from Clock__c where Lead__c IN: update_leads.keySet()]);
				Map<ID, Clock__c> leadClocks = new Map<ID, Clock__c>();
				for(Clock__c ck : extClocks){
					leadClocks.put(ck.Lead__c, ck);
				}
				
				for(Lead l : update_leads.values()){				
					if(l.IsOver7Days__c){
						System.debug('Test 7 days over');	
						l.Is7DaysEnabled__c = false;
						if(!l.IsConverted){// if not converted
							//change owner
							ID oldOwnerId = l.OwnerId;
							l.OwnerId = ownerIDsQueueIDs.get(l.OwnerId);
							System.debug('Test Over first 7 dyas OwnerID changed from ' + oldOwnerId + ' To ' + l.OwnerId);	
							//send email
							Messaging.SingleEmailMessage nEmail;
					    	nEmail = new Messaging.SingleEmailMessage();
					    	System.debug('Test setTargetObjectId = ' + oldOwnerId);
					    	nEmail.setReplyTo(LeadSharkpoolClass.SenderEmail);	
							nEmail.setSenderDisplayName(LeadSharkpoolClass.SenderDisplayName);	
							nEmail.setTargetObjectId(oldOwnerId);
							nEmail.setsaveAsActivity(false);
							nEmail.setUseSignature(false);	
							nEmail.setSubject('Alert : Lead was assigned to the Shark Pool');
							String l_name = (l.Name == null)? 'n/a'	: l.Name;						
							String HtmlEmailContent = 
		'Please note that your are no longer the owner of the following lead:'
	  + '<p/>'
	  + '<table border="0" width="1000">'
	  + '<tr>'
	  + '<th align="left">Lead ID</th><th align="left">Name</th><th align="left">Company</th>'
	  + '<th align="left">Lead Status</th><th align="left">Lead Source</th><th align="left">Created Date</th>'
	  + '</tr>'
	  + '<tr>'
	  + '<td align="left"><a href="https://' + LeadSharkpoolClass.SFDC_DOMAIN + '/'+l.Id+'">'+l.Id +'</a></td>'+ 
	  + '<td align="left">' + l_name +'</td><td align="left">'+l.Company+'</td><td align="left">'+l.Status+'</td>'
	  + '<td align="left">'+l.LeadSource+'</td><td align="left">'+l.CreatedDate+'</td>'
	  + '</tr>'
	  + '</table>'
	  + '<p/>'
	  + 'This Lead has been re-assigned to the <b>'+ queues.get(l.OwnerId).Name + '</b>. You can re-claim the leads at any time as long as no one else has claimed them before you.<p>'; 
	                        nEmail.setHtmlBody(HtmlEmailContent);
							messages.add(nEmail);
							System.debug('Test email message created');
						}
					}else{
						l.Is7DaysEnabled__c = true; //set default value to start 1st time-based workflow
						Lead oldLead = trigger.oldMap.get(l.Id);
						if(oldLead.OwnerId != l.OwnerId 
						|| LeadSharkpoolClass.ExLeadSourceNames.contains(oldLead.LeadSource)
						|| LeadSharkpoolClass.ExLeadStatusNames.contains(oldLead.Status)
						|| l.Latest_Owner_Change_Date__c == null) {
							l.Latest_Owner_Change_Date__c = DateTime.now();
						}					
					}	
					if(!l.IsConverted && !l.IsOver7Days__c){// if not converted
						Clock__c clk;						
						if(leadClocks.containsKey(l.Id)){
							clk = leadClocks.get(l.Id);
						}else{
							clk = new Clock__c();
							clk.Lead__c = l.Id;
						}					
						clk.isClockEnabled__c = l.Is7DaysEnabled__c;
						clk.Latest_Owner_Change_Date__c = l.Latest_Owner_Change_Date__c;	
						upsert_clocks_in_before.add(clk);
					}					
					l.IsOver7Days__c = false;	
				}	
			}	
			
			System.debug('Test before upsert_clocks_in_before.size() = ' + upsert_clocks_in_before.size());
			if(!upsert_clocks_in_before.isEmpty()){
				upsert upsert_clocks_in_before;
			}	
					
			System.debug('Test messages.isEmpty() = ' + messages.isEmpty());	
			if(!messages.isEmpty()){
				//System.debug('messages size = ' + messages.size());	
				Integer size = messages.size();
				Messaging.SingleEmailMessage[] emails = new Messaging.SingleEmailMessage[size];
				for(Integer i = 0; i < size ; i++){
					System.debug('Test ' + i + '; TargetObjectId = ' + messages[i].getTargetObjectId());	
					emails[i] = messages[i];
				}
				Messaging.SendEmailResult[] eResult;
				try{
					eResult = Messaging.sendEmail(emails);
					for(Messaging.SendEmailResult r : eResult){
					  System.debug('Test email sent + ' + r.isSuccess());	
					}
				}catch(Exception ex){
					System.debug('Test Email send failed ' + ex);
				}
			}
	   }
	}else if(trigger.isAfter){
	   List<Clock__c> upsert_clocks_in_after = new List<Clock__c>();		
	   if(LeadSharkpoolClass.getIsFirstAfter())	{	   
		    LeadSharkpoolClass.setIsFirstAfter(false);
			List<Clock__c> del_clocks = new List<Clock__c>();
			Set<ID> invalidLeadIDs = new Set<ID>();
			
			if(trigger.isInsert){
				for(Lead l : trigger.new){
					String s = string.valueof(l.OwnerId);
					Boolean isMatched = (l.RecordTypeId == leadRecordTypeId) && !LeadSharkpoolClass.ExLeadSourceNames.contains(l.LeadSource) 
					                                && !LeadSharkpoolClass.ExLeadStatusNames.contains(l.Status)
					                                && s.substring(0, 3) != Queue_Prefix;                                       	
					if(isMatched){
						Clock__c clk = new Clock__c();
						clk.Lead__c = l.Id;					
						clk.isClockEnabled__c = l.Is7DaysEnabled__c;
						clk.Latest_Owner_Change_Date__c = l.Latest_Owner_Change_Date__c;
						upsert_clocks_in_after.add(clk);
					}
				}
			}else if(trigger.isUpdate){
				for(Lead l : trigger.new){
					String s = string.valueof(l.OwnerId);     
					if(l.RecordTypeId == leadRecordTypeId && (l.isConverted || !l.Is7DaysEnabled__c 
					                                          || LeadSharkpoolClass.ExLeadSourceNames.contains(l.LeadSource)
					                                          || LeadSharkpoolClass.ExLeadStatusNames.contains(l.Status))
					                                          || s.substring(0, 3) == Queue_Prefix){
						invalidLeadIDs.add(l.Id);
					}			
				}
			}else if(trigger.isDelete){
				for(Lead oldLead : trigger.old){
					if(oldLead.RecordTypeId == leadRecordTypeId){   
						invalidLeadIDs.add(oldLead.Id);
						break; // Lead record has been deleted from the database, not commit yet
					}			
				}
			}
			
			System.debug('Test after upsert_clocks_in_after.size() = ' + upsert_clocks_in_after.size());
			if(!upsert_clocks_in_after.isEmpty()){
				insert upsert_clocks_in_after;
			}	
								
			System.debug('Test delete clock__c record = ' + invalidLeadIDs.size());
			if(!invalidLeadIDs.isEmpty()){
				del_clocks = [select ID, Lead__c from Clock__c where Lead__c IN: invalidLeadIDs or Lead__c = null];
				if(!del_clocks.isEmpty()){
					delete del_clocks;
				}
			} 
	   }
	}
	*/
}